package com.leeyu.rabbitmq.rpc;

import com.leeyu.rabbitmq.util.RabbitMQConnectionUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class Publisher {

    private static final String QUEUE_PUBLISHER = "rpc-publisher";
    private static final String QUEUE_CONSUMER = "rpc-consumer";

    @Test
    public void publish() throws Exception {
        // 获取连接
        Connection connection = RabbitMQConnectionUtil.getConnection();

        // 构建channel
        Channel channel = connection.createChannel();

        // 构建队列
        channel.queueDeclare(QUEUE_PUBLISHER, false, false, false, null);
        channel.queueDeclare(QUEUE_CONSUMER, false, false, false, null);

        String uuid = UUID.randomUUID().toString();
        AMQP.BasicProperties properties = new AMQP.BasicProperties()
                .builder()
                .replyTo(QUEUE_CONSUMER)
                .correlationId(uuid)
                .build();
        // 发送消息
        channel.basicPublish("", QUEUE_PUBLISHER, properties, "Hello RPC！".getBytes(StandardCharsets.UTF_8));

        // 监听QUEUE_CONSUMER
        channel.basicConsume(QUEUE_CONSUMER, false, new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
               String id = properties.getCorrelationId();
               if (id != null && id.equals(uuid)) {
                   System.out.println("接收到服务端响应：" + new String(body, StandardCharsets.UTF_8));
                   channel.basicAck(envelope.getDeliveryTag(), false);
               }
           }
        });

        System.out.println("消息发送成功！");

        System.in.read();
    }
}
